package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/18 20:38
 */
public class UserService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public static Map<String, User> map = new HashMap<>();
    static{
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword("admin");

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword("1234");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }




    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username:"+username);
        User user = map.get(username);
        if (user == null) {
            return null;
        }
        String password = user.getPassword();
        //当前用户的登陆授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("add"));
        list.add(new SimpleGrantedAuthority("permission_B"));
        if (username.equals("admin")){
            //授予角色，框架默认 ROLE_ 授予角色，如果不是则认为是权限
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,"{noop}" + password,list);
        return userDetails;

        /*System.out.println("username:" + username);
        return null;//return null 永远登陆不成功*/





    }
}
